package com.glela.controller;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.User;
import com.glela.platform.model.UserPayInfo;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.service.SmsService;
import com.glela.platform.service.UserPayInfoService;
import com.glela.platform.service.UserService;
/** 
* @ClassName: UserPasswordController 
* @Description: 重置用户密码逻辑控制层
* @author zhangrenjie
* @date 2017年8月10日 下午3:32:55 
*  
*/
@Controller
@RequestMapping(value = "/password")
public class UserPasswordController {
	private static Logger logger = LoggerFactory.getLogger(UserPasswordController.class);
	@Autowired
	private SmsService smsService;
	@Autowired
	private UserService userService;
	@Autowired
	private UserPayInfoService userPayInfoService;
	
	/** 
	* @Title: sendMessageCode 
	* @Description: 根据不同业务类型发送短信验证码
	* @param @param datas
	* @param @return    设定文件 
	* @return ResponseEntity<?>    返回类型 
	* @throws 
	* @author zhangrenjie 
	* @date 2017年8月14日 上午11:11:23 
	*/
	@RequestMapping(value = "/sendMessageCode", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> sendMessageCode (@RequestBody Map<String, String> datas) {
		try {
			if (datas.isEmpty()) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if (StringUtils.isEmpty(datas.get("type")) || StringUtils.isEmpty(datas.get("mobile")) ||StringUtils.isEmpty(datas.get("userId"))) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if ( !"2".equals(datas.get("type"))  && !"3".equals(datas.get("type")) && !"4".equals(datas.get("type"))&& !"5".equals(datas.get("type")) ){//校验类型
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
			}
			String type = datas.get("type"),mobile = datas.get("mobile"),userId = datas.get("userId");
			boolean b = smsService.sendNumberVerifyCodeSms(mobile, type, userId);
			//			String s2 = "您正在找回登录密码，验证码为%s（切勿告知他人），30分钟内有效。如有问题请及时联系客服400-036-9090【校妆网】";
			//			String s3 = "您正在设置支付密码，验证码为%s（切勿告知他人），30分钟内有效。如有问题请及时联系客服400-036-9090【校妆网】"; 
			//			String s4 = "您正在找回支付密码，验证码为%s（切勿告知他人），30分钟内有效。如有问题请及时联系客服400-036-9090【校妆网】";
			//			String s5 = "您正在设置登录密码，验证码为%s（切勿告知他人），30分钟内有效。如有问题请及时联系客服400-036-9090【校妆网】";
			//			if ("3".equals(type)) {
			//				b = smsService.sendNumberVerifyCodeSms(mobile, Integer.parseInt(type),userId,s3);
			//			}else if ("4".equals(type)) {
			//				b = smsService.sendNumberVerifyCodeSms(mobile, Integer.parseInt(type),userId,s4);
			//			}else if ("2".equals(type)) {
			//				b = smsService.sendNumberVerifyCodeSms(mobile, Integer.parseInt(type),userId,s2);
			//			} else if ("5".equals(type)) {
			//				b = smsService.sendNumberVerifyCodeSms(mobile, Integer.parseInt(type),userId,s5);
			//			}
			if (b) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
			}else {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20112), HttpStatus.OK);
			}
		}catch (Exception e) {
			logger.error("发送短信异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/** 
	* @Title: checkMessageCode 
	* @Description: 根据类型校验短信验证码
	* @param @param datas
	* @param @return    设定文件 
	* @return ResponseEntity<?>    返回类型 
	* @throws 
	* @author zhangrenjie 
	* @date 2017年8月14日 上午11:10:56 
	*/
	@RequestMapping(value = "/checkMessageCode", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> checkMessageCode(@RequestBody Map<String, String> datas) {
		try {
			if (datas.isEmpty()) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if (StringUtils.isEmpty(datas.get("type")) || StringUtils.isEmpty(datas.get("mobile")) ||StringUtils.isEmpty(datas.get("code"))) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			int i = smsService.validateVerifyCode(datas.get("mobile"), datas.get("type"), datas.get("code"));
			if (i==1) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
			}else {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20126), HttpStatus.OK);
			}
		} catch (Exception e) {
			logger.error("校验验证码异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	/** 
	* @Title: resetLoginPassword 
	* @Description: 找回登录密码 
	* @param @param datas
	* @param @return    设定文件 
	* @return ResponseEntity<?>    返回类型 
	* @throws 
	* @author zhangrenjie 
	* @date 2017年8月14日 上午11:10:40 
	*/
	@RequestMapping(value = "/resetLoginPassword", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> resetLoginPassword(@RequestBody Map<String, String> datas) {
		try {
			if (datas.isEmpty()) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if (StringUtils.isEmpty(datas.get("userId")) || StringUtils.isEmpty(datas.get("password"))) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			String password = datas.get("password"),userId = datas.get("userId");
			//校验密码
//			if (checkMobileAndPassword(userId, password)) {
//				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C25004), HttpStatus.OK);
//			}
			if (checkloginAndPay(userId, password, "0")) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C25006), HttpStatus.OK);
			}
			User user = userService.getUser(Long.parseLong(userId));
			if (null != user) {//重置登录密码
				int i = userService.resetUserPasswordByUserId(user.getId(),password);//重置密码
				if (1 == i) {
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
				}else {
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20121), HttpStatus.OK);
				}
			}
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20121), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("找回登录密码异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	/** 
	* @Title: resetPayPassword 
	* @Description: 找回支付密码
	* @param @param datas
	* @param @return    设定文件 
	* @return ResponseEntity<?>    返回类型 
	* @throws 
	* @author zhangrenjie 
	* @date 2017年8月14日 上午11:14:07 
	*/
	@RequestMapping(value = "/resetPayPassword", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> resetPayPassword(@RequestBody Map<String, String> datas) {
		try {
			if (datas.isEmpty()) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if (StringUtils.isEmpty(datas.get("userId")) || StringUtils.isEmpty(datas.get("password"))) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			String password = datas.get("password"),userId = datas.get("userId");
			//校验密码
//			if (checkMobileAndPassword(userId, password)) {
//				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C25004), HttpStatus.OK);
//			}
			if (checkloginAndPay(userId, password, "1")) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C25005), HttpStatus.OK);
			}
			User user = userService.getUser(Long.parseLong(userId));
			if (null == user) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20111), HttpStatus.OK);
			}
			UserPayInfo uInfo = userPayInfoService.queryUserPayInfoByUserId(userId);
			if (null != uInfo) {
				int i = userPayInfoService.resetPayPassword(userId,password);
				if (1 == i) {
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
				}else {
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20121), HttpStatus.OK);
				}
			}
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20121), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("修改支付密码异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	/** 
	* @Title: setPayPassword 
	* @Description: 初次设置支付密码 
	* @param @param datas
	* @param @return    设定文件 
	* @return ResponseEntity<?>    返回类型 
	* @throws 
	* @author zhangrenjie 
	* @date 2017年8月14日 上午11:17:23 
	*/
	@RequestMapping(value = "/setPayPassword", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> setPayPassword(@RequestBody Map<String, String> datas) {
		try {
			if (datas.isEmpty()) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if (StringUtils.isEmpty(datas.get("userId")) || StringUtils.isEmpty(datas.get("password"))) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			String password = datas.get("password"),userId = datas.get("userId");
			//校验密码
//			if (checkMobileAndPassword(userId, password)) {
//				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C25004), HttpStatus.OK);
//			}
			if (checkloginAndPay(userId, password, "1")) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C25005), HttpStatus.OK);
			}
			User user = userService.getUser(Long.parseLong(userId));
			if (null == user) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20111), HttpStatus.OK);
			}
			UserPayInfo uInfo = userPayInfoService.queryUserPayInfoByUserId(userId);
			if (null == uInfo) {
				UserPayInfo userPayInfo = new UserPayInfo();
				userPayInfo.setUserId(Long.parseLong(userId));
				userPayInfo.setPwd(password);
				userPayInfo.setStatus(new Byte("1"));
				int i = userPayInfoService.insetNewOne(userPayInfo);
				if (1 == i) {
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
				}else {
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20121), HttpStatus.OK);
				}
			}
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20121), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("修改密码异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	//////////////////////////////////////////////////////////////////////////////////////////////////////////
/*	private boolean checkMobileAndPassword(String userId,String password) {
		User user = userService.getUser(Long.parseLong(userId));
		if (null!= user) {
			if (!StringUtils.isEmpty(user.getUserName())) {
//			String mobile = user.getUserName();
//			String mobile = MD5Utils.encrypt(user.getUserName());
				String mobile = DigestUtils.md5Hex(user.getUserName());//MD5
				if (mobile.equals(password)) {
					return true;
				}
			}
		}
		return false;
	}*/
	private boolean checkloginAndPay(String userId,String password,String type) {
		if ("0".equals(type)) {//登录
			UserPayInfo payInfo = userPayInfoService.queryUserPayInfoByUserId(userId.toString());
			if (null != payInfo) {
				if (!StringUtils.isEmpty(payInfo.getPwd())) {
					if (payInfo.getPwd().equals(password)) {
						return true;
					}
				}
			}
		}else if ("1".equals(type)) {//支付
			User user = userService.getUser(Long.parseLong(userId));
			if (null != user) {
				if (!StringUtils.isEmpty(user.getPassword())) {
					if (user.getPassword().equals(password)) {
						return true;
					}
				}
			}
		}
		return false;
	}
}
